# coding: utf-8  

from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.views.decorators.csrf import csrf_protect
from django.template import loader, RequestContext
from django.contrib.auth import authenticate, login as auth_login
from django.views.decorators.cache import never_cache
from django.core.exceptions import ObjectDoesNotExist
import django.utils.timezone as timezone
import os

from django.http import HttpResponse
from django.shortcuts import render_to_response

from testlove.my_form import ContactForm,PictureForm
from books.models import Product,NameList

HERE = os.path.dirname(os.path.abspath(__file__))

def addPicture(request):  
    if request.method == 'POST':  
        form = PictureForm(request.POST, request.FILES)  
        if form.is_valid():  
            print '-------i am in the if 2---------'
            sub_path = os.path.join(HERE,'img')
            f = request.FILES["imagefile"]  
            des_origin_path = os.path.join(sub_path,str(f))
            print 'des_origin_path= ',des_origin_path
            # des_origin_path 为你在服务器上保存原始图片的文件物理路径  
            des_origin_f = open(des_origin_path, "ab")  
            for chunk in f.chunks():  
                des_origin_f.write(chunk)  
            des_origin_f.close()
            return render_to_response('addpicture_output.html', {'picture': str(f)})                      
    else:
        form = PictureForm()
    return render_to_response('addpicture.html', {'form': form},RequestContext(request))
 

def info_view(request):
    
    #return render_to_response("main_view.html", {'username': request.user.username})
    return render_to_response("info.html", {'info': 'wo ai ni'})
        
def search(request):
    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']
        #books = 'there is not database!'
        books = Product.objects.filter(name=q)
        #print 'books[0].pub_date',books[0].pub_date
        return render_to_response('search_results.html',
            {'books': books, 'query': q})
    else:
        return render_to_response('search.html')

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            p = NameList(subject=cd['subject'],email=cd['email'],message=cd['message'])
            p.save()
            #return render_to_response('database.html',{'subject':cd['subject'],'message':cd['message'],'email':cd['email']})
            return HttpResponse(cd['subject'],cd['message'],cd['email'])
    else:
        form = ContactForm()
    return render_to_response('contact_form.html', {'form': form},RequestContext(request))
    
def home(request):
    #return render_to_response("main_view.html", {'username': request.user.username})
    return render_to_response("home.html")